package com.iocup.keybastion.core.impl;


import com.iocup.keybastion.authentication.AccessToken;
import com.iocup.keybastion.context.SecurityContextHolder;
import com.iocup.keybastion.core.RefreshTokenActionLogic;
import com.iocup.keybastion.core.client.Client;
import com.iocup.keybastion.core.client.ClientFinder;
import com.iocup.keybastion.core.profile.UserProfile;
import com.iocup.keybastion.exception.AuthenticationException;
import com.iocup.keybastion.utils.NameUtils;
import com.pine.sunflower.core.validate.Validator;

import java.util.Optional;

/**
 * @author xyjxust
 * @create 2022/3/15 13:59
 **/
public class DefaultRefreshTokenActionLogic implements RefreshTokenActionLogic {

    private ClientFinder clientFinder;

    public DefaultRefreshTokenActionLogic clientFinder(ClientFinder clientFinder) {
        Validator.build().validate(clientFinder == null, "clientFinder不能为空")
                .throwIfFail();
        this.clientFinder = clientFinder;
        return this;
    }

    @Override
    public AccessToken refresh() {
        //检查必要的配置信息
        Validator.build().validate(SecurityContextHolder.getContext() == null, "请配置MatchingLogicChecker在此检查器之前执行")
                .throwIfFail();
        Optional<Client> optionalClient = clientFinder.find(NameUtils
                .getClientName(SecurityContextHolder.getContext().getWebContextHolder()));
        if(!optionalClient.isPresent()){
            throw new AuthenticationException("clientName错误");
        }
       Optional<UserProfile> optionalUserProfile =   optionalClient.get().refreshUserDetail(SecurityContextHolder.getContext().getWebContextHolder());
       if(!optionalClient.isPresent()){
           throw new AuthenticationException("刷新token已过期");
       }
       SecurityContextHolder.getContext().setUserProfile(optionalUserProfile.get());
       return SecurityContextHolder.getContext().getToken();
    }

}
